package repository.impl;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import repository.UserRepository;
import domain.User;
import domain.exceptions.DuplicateException;


@Repository
public class UserRepositoryImpl extends AbstractHibernateRepository<User> implements UserRepository{

	@Autowired
	public UserRepositoryImpl(SessionFactory sessionfactory){
		super(sessionfactory);
	}
	
	public User validate(String username, String password) {
		String hql = "FROM User WHERE username=? AND password=?";
		List<User> result = find(hql, username, password);
		return result.isEmpty() ? null : result.get(0);
	}

	public User getUser(int id) {
		return get(User.class, id);
	}
	
	public User getUserByUserName(String userName) {
		String hql = "FROM User WHERE username=?";
		List<User> result = find(hql, userName);
		return result.isEmpty() ? null : result.get(0);
	}
	
	public User getUserByEmail(String email) {
		String hql = "FROM User WHERE email=?";
		List<User> result = find(hql, email);
		return result.isEmpty() ? null : result.get(0);
	}
	
	public User getUser(String userName, String email) {
		String hql = "FROM User WHERE username=? AND email=?";
		
		List<User> result = find(hql, userName, email);
		return result.isEmpty() ? null : result.get(0);
	}
	
	public void newUser(User user)throws DuplicateException{
		if(getUserByUserName(user.getUserName())==null && getUserByEmail(user.getEmail())==null) {
			save(user);
		}else{
			throw new DuplicateException();
		}
	}

	@Override
	public List<User> getRegisteredUsers() {
		String hql = "FROM User ORDER BY lastAccess DESC";
		return find(hql);		
	}

	@Override
	public List<User> getDebtUsers() {
		String hql = "SELECT DISTINCT p.item.user FROM Purchase as p WHERE p.debtPending = true";
		return find(hql);
	}
	
	@Override
	public List<User> getPointsFromAll(String order){
		if(order==null || order.isEmpty()){
			order="positive";
		}
		String hql = "From User Order By " + order + " DESC";
		return find(hql);
	}
}